package cn.zqh.auth.service;

import cn.hutool.core.collection.CollUtil;
import cn.zqh.auth.constant.MessageConstant;
import cn.zqh.auth.domain.SecurityUser;
import cn.zqh.auth.domain.SecurityUserPlus;
import cn.zqh.auth.domain.UserDTO;
import cn.zqh.auth.domain.UserPlus;
import cn.zqh.auth.mapper.UserMapper;
import cn.zqh.auth.pojo.User;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AccountExpiredException;
import org.springframework.security.authentication.CredentialsExpiredException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 用户管理业务类
 * Created by macro on 2020/6/19.
 */
@Service
public class AuthUserServiceImpl implements UserDetailsService {

    private List<UserDTO> userList;
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Resource
    private UserMapper userMap;

    @PostConstruct
    public void initData() {
        String password = passwordEncoder.encode("123456");
        userList = new ArrayList<>();
        userList.add(new UserDTO(1L,"macro", password,1, CollUtil.toList("ADMIN")));
        userList.add(new UserDTO(2L,"andy", password,1, CollUtil.toList("TEST")));
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {


        User user = userMap.selectOne(new QueryWrapper<User>().eq("Qq_email", username));
        if (user == null){
            throw new UsernameNotFoundException("用户不存在");
        }
        System.out.println(passwordEncoder.encode("123456"));
        //开始
        System.out.println(username);
        List<String> roleCodeByEmail = userMap.getRoleCodeByEmail(username);
        System.out.println(roleCodeByEmail);
        System.out.println(user);
        if (user == null){
            throw new UsernameNotFoundException(MessageConstant.USERNAME_PASSWORD_ERROR);
        }


        ArrayList<GrantedAuthority> grantedAuthorities = new ArrayList<>();
        for (String role : roleCodeByEmail) {
            SimpleGrantedAuthority adminAuth = new SimpleGrantedAuthority(role);
            grantedAuthorities.add(adminAuth);
        }
        SecurityUser securityUser = new SecurityUser().setId(user.getUserId()).setUsername(user.getQqEmail())
                .setPassword(user.getPassword()).setEnabled(user.getIsDelete() == 0).setAuthorities(grantedAuthorities);

//        return new SecurityUserPlus()
//                .setQqEmail(user.getQqEmail())
//                .setEnabled(user.getIsDelete() == 1)
//                .setId(user.getUserId())
//                .setPassword(user.getPassword())
//                .setAuthorities(grantedAuthorities);
        //结束
        //自带
//        List<UserDTO> findUserList = userList.stream().filter(item -> item.getUsername().equals(username)).collect(Collectors.toList());
//        if (CollUtil.isEmpty(findUserList)) {
//            throw new UsernameNotFoundException(MessageConstant.USERNAME_PASSWORD_ERROR);
//        }
//        SecurityUser securityUser = new SecurityUser(findUserList.get(0));
        //自带

//        List<String> roleCodeByEmail = userMap.getRoleCodeByEmail(username);
//        ArrayList<GrantedAuthority> grantedAuthorities = new ArrayList<>();
//        for (String role : roleCodeByEmail) {
//            SimpleGrantedAuthority simpleGrantedAuthority = new SimpleGrantedAuthority(role);
//            grantedAuthorities.add(simpleGrantedAuthority);
//        }
//        SecurityUser securityUser = new SecurityUser();
//        securityUser.setId(user.getUserId())
//                .setPassword(user.getPassword())
//                .setEmail(user.getQqEmail())
//                .setAuthorities(grantedAuthorities)
//                .setEnabled(user.getIsDelete()==0);


        //自带

        if (!securityUser.isEnabled()) {
            throw new DisabledException(MessageConstant.ACCOUNT_DISABLED);
        } else if (!securityUser.isAccountNonLocked()) {
            throw new LockedException(MessageConstant.ACCOUNT_LOCKED);
        } else if (!securityUser.isAccountNonExpired()) {
            throw new AccountExpiredException(MessageConstant.ACCOUNT_EXPIRED);
        } else if (!securityUser.isCredentialsNonExpired()) {
            throw new CredentialsExpiredException(MessageConstant.CREDENTIALS_EXPIRED);
        }
        System.out.println(securityUser);
        return securityUser;
        //自带

    }

}
